package com.automapper.criterion;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.automapper.utils.ObjectFacade;

public class SqlAssemble {

	private Map<Class<?>, String> aliasMap = new HashMap<>();
	private Map<Class<?>, String> tableNameMap = new HashMap<>();
	private Class<?> clazz = null;
	private Class<?> associationClazz = null;
	
	public void setTableName(Class<?> clazz, String tableName) {
		tableNameMap.put(clazz, tableName);
	}
	
	public String getTableName(Class<?> clazz) {
		return tableNameMap.get(clazz);
	}
	
	public void setAlias(Class<?> clazz, String alias) {
		aliasMap.put(clazz, alias);
	}
	
	public String getAlias(Class<?> clazz) {
		return aliasMap.get(clazz);
	}

	public void setClazz(Class<?> clazz) {
		this.clazz = clazz;
	}
	
	public Class<?> getClazz() {
		return clazz;
	}

	public void setAssociationClazz(Class<?> associationClazz) {
		this.associationClazz = associationClazz;
	}

	public Class<?> getAssociationClazz() {
		return associationClazz;
	}
	
	public List<String> assembleColumn() throws Exception {
		List<String> columnNames = new ArrayList<>();
		columnNames.addAll(assembleColumn(clazz));
		columnNames.addAll(assembleColumn(associationClazz));	
		return columnNames;
	}
	
	public List<String> assembleTable() {
		List<String> tables = new ArrayList<>();
		tables.addAll(assembleTable(clazz));
		tables.addAll(assembleTable(associationClazz));
		return tables;
	}
	
	private List<String> assembleColumn(Class<?> clazz) throws Exception {
		List<String> list = new ArrayList<>();
		if (clazz != null) {
			List<String> tmp = new ObjectFacade(clazz.newInstance()).getColumnNames();
			for (String column : tmp) {
				String alias = aliasMap.get(clazz);
				list.add(alias + "." + column + " as " + alias + column);
			}
		}
		return list;
	}
	
	private List<String> assembleTable(Class<?> clazz) {
		List<String> list = new ArrayList<>();
		if (clazz != null) {
			String alias = aliasMap.get(clazz);
			list.add(tableNameMap.get(clazz) + " " + alias);
		}
		return list;
	}
}
